package com.abso.mp3tunes.locker.ui.actions;

import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

import com.abso.mp3tunes.locker.core.LockerServiceException;
import com.abso.mp3tunes.locker.core.data.Playlist;
import com.abso.mp3tunes.locker.core.data.PlaylistData;
import com.abso.mp3tunes.locker.ui.LockerPlugin;
import com.abso.mp3tunes.locker.ui.dialogs.PlaylistNameValidator;
import com.abso.mp3tunes.locker.ui.viewers.LockerViewer;

/**
 * Action able to rename a playlist.
 */
public class RenamePlaylistAction extends AbstractLockerViewerAction {

	/** The playlist being renamed. */
	private Playlist playlist;

	/**
	 * Constructs a new action.
	 * 
	 * @param lockerViewer
	 *            the Locker tree viewer.
	 */
	public RenamePlaylistAction(LockerViewer lockerViewer) {
		super("Rename...", null, lockerViewer);
	}

	/**
	 * Sets the playlist being renamed.
	 * 
	 * @param playlist
	 *            the playlist being renamed.
	 */
	public void setPlaylist(Playlist playlist) {
		this.playlist = playlist;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.jface.action.Action#run()
	 */
	public void run() {
		final InputDialog inputDialog = new InputDialog(LockerPlugin
				.getActiveWorkbenchShell(), "Rename Playlist", "New name:",
				playlist.getTitle(), new PlaylistNameValidator(playlist
						.getTitle()));
		if (inputDialog.open() != Window.OK) {
			return;
		}
		try {
			String newTitle = inputDialog.getValue();
			PlaylistData result = LockerPlugin.getDefault().getLockerService()
					.renamePlaylist(playlist.getId(), newTitle);
			if (result.getStatus() == 1) {
				Shell shell = LockerPlugin.getActiveWorkbenchShell();
				Display display = shell.getDisplay();
				BusyIndicator.showWhile(display, new Runnable() {
					public void run() {
						getLockerViewer().setDirty();
						getLockerViewer().updateContent();
					}
				});
			}
		} catch (LockerServiceException e) {
			showErrorDialog("Error", "Unable to rename the playlist",
					"Error renaming the playlist", e);
		}

	}

}
